var express = require("express");
var router = express.Router();
const dayjs = require("dayjs");
const WebSocket = require("ws");
var multiparty = require("multiparty");
const path = require("path");
const { promisify } = require("util");
const fs = require("fs");
const { uploadImage } = require("../../utils/common");
const authMiddleWare = require("../../middleWare/auth");

const { getResult, getList } = require("../../utils/sql");
const { getWebSocketServer } = require("../../utils/websocketManager");

let DATABASE = "suggestion_list";
let DATABASE1 = "suggestion_reply_list";

router.get("/list", authMiddleWare, async function (req, res) {
  let { keyword, page, limit, selfFlag, sortType, sortProp, status, type } =
    req.query;
  let sql = `SELECT * FROM ${DATABASE} WHERE 1=1`;
  if (!page || !limit) {
    res.send({
      code: 0,
      message: "no Page Limit",
    });
    return;
  }
  const offset = (page - 1) * limit;
  let paramsList = [];
  if (keyword) {
    sql += " AND title like ? OR content like ? ";
    paramsList.push(...[`%${keyword}%`, `%${keyword}%`]);
  }
  if (selfFlag) {
    sql += selfFlag === "1" ? " AND user_id=?" : " AND user_id != ?";
    paramsList.push(req.auth);
  }
  if (status) {
    sql += " AND status=?";
    paramsList.push(status);
  }
  if (type) {
    sql += " AND type=?";
    paramsList.push(type);
  }

  if (sortType === "1") {
    if (sortProp) {
      sql += ` ORDER BY ${sortProp} ASC`;
    } else {
      sql += ` ORDER BY id ASC`;
    }
  } else {
    if (sortProp) {
      sql += ` ORDER BY ${sortProp} DESC`;
    } else {
      sql += " ORDER BY id DESC";
    }
  }
  // 分页
  sql += ` LIMIT ${limit} OFFSET ${offset}`;
  paramsList.push(limit, offset);

  let result = await getResult({
    sql,
    paramsList,
  });

  result[0].forEach((item) => {
    item.create_time = dayjs(item.create_time).format("YYYY-MM-DD HH:mm:ss");
  });

  let result1 = await getResult({
    sql: `SELECT COUNT(*) AS count FROM ${DATABASE}`,
    paramsList: [],
  });

  let result2 = await getResult({
    sql: `SELECT COUNT(*) AS count FROM ${DATABASE} WHERE user_id=?`,
    paramsList: [req.auth],
  });

  res.send({
    code: 0,
    data: result[0],
    total: result1[0][0].count,
    myTotal: result2[0][0].count,
    message: "OK",
  });
});

router.post("/add", authMiddleWare, async function (req, res) {
  let { title, content, type, username } = req.body;

  let sql = `INSERT INTO ${DATABASE}
  (title,content,type,see,user_id, user_name)
  value(?,?,?,?,?,?)`;
  let paramsList = [title, content, type, 1, req.auth, username];
  await getResult({
    sql,
    paramsList,
  });

  res.send({
    code: 0,
    message: "add Successfully",
  });
});

router.get("/detail", authMiddleWare, async function (req, res) {
  let id = req.query.id;
  let sql = `UPDATE ${DATABASE} SET see = see + 1`;
  let paramsList = [id];
  if (req.auth == "2") {
    sql += `, status = 1`;
  }
  sql += ` WHERE id=?`;
  await getResult({
    sql,
    paramsList,
  });

  getList(DATABASE, ["id"], [id]).then((result) => {
    result.forEach((item) => {
      item.create_time = dayjs(item.create_time).format("YYYY-MM-DD HH:mm:ss");
    });
    res.send({
      code: 0,
      data: result[0],
      message: "OK",
    });
  });
});

// 上传图片到腾讯云cos
router.post("/upload", async function (req, res) {
  var multipart = new multiparty.Form();
  multipart.parse(req, async function (err, fields, files) {
    const file = files["wangeditor-uploaded-image"][0];
    let lastDotIndex = file.originalFilename.lastIndexOf(".");
    let type = file.originalFilename.slice(lastDotIndex + 1);
    let name = file.originalFilename.slice(0, lastDotIndex);
    const readFile = promisify(fs.readFile);
    const fileBuffer = await readFile(file.path);
    let result = await uploadImage(fileBuffer, type, name);
    res.send({
      code: 0,
      message: "OK",
      data: {
        url: result, // 图片 src ，必须
        alt: name, // 图片描述文字，非必须
        href: result, // 图片的链接，非必须
      },
    });
  });
});

router.get("/reply/list", authMiddleWare, async function (req, res) {
  getList(DATABASE1, ["suggestion_id"], [req.query.suggestionId]).then(
    (result) => {
      result.forEach((item) => {
        item.create_time = dayjs(item.create_time).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      });
      res.send({
        code: 0,
        data: result,
        message: "OK",
      });
    }
  );
});

router.post("/reply", authMiddleWare, async function (req, res) {
  let { suggestionId, content, username, createUserId, title } = req.body;

  let sql = `INSERT INTO ${DATABASE1}
  (suggestion_id,content,user_id,user_name)
  value(?,?,?,?)`;
  let paramsList = [suggestionId, content, req.auth, username];
  await getResult({
    sql,
    paramsList,
  });

  let sql1 = `UPDATE ${DATABASE}
  SET comment_num = comment_num + 1
  WHERE id=?
  `;
  await getResult({
    sql: sql1,
    paramsList: [suggestionId],
  });

  const wss = getWebSocketServer();
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(
        JSON.stringify({
          id: createUserId,
          title,
          suggestionId,
        })
      );
    }
  });

  res.send({
    code: 0,
    message: "add Successfully",
  });
});

module.exports = router;
